<template>
    <div class="home">
        <input v-model="user.firstName" />
        <input v-model="user.lastName" />
        <div>-----------------------------------------------------------------------</div>
        computed: <input v-model="name1" /> watch(第一个参数为单一变量):
        <input v-model="name2" /> watch(第一个参数为数组): <input v-model="name3" /> watchEffect:
        <input v-model="name4" />
    </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, watch, watchEffect } from "vue";
// import { Vue } from "vue-class-component";

export default defineComponent({
    setup() {
        const user = reactive({ firstName: "范", lastName: "佳东" });
        const name1 = computed(() => `${user.firstName}_${user.lastName}`);
        const name2 = ref("");
        watch(
            user,
            newV => {
                name2.value = `${newV.firstName}_${newV.lastName}`;
            },
            { immediate: true }
        );
        const name3 = ref("");
        //监听的变量为响应式时才能直接写，否则得用函数返回才能监听
        watch(
            [() => user.firstName, () => user.lastName],
            ([newFirstName, newLastName]) => {
                name3.value = `${newFirstName}_${newLastName}`;
            },
            { immediate: true }
        );
        watch(
            () => user.firstName,
            newV => {
                console.log(newV);
            }
        );
        const name4 = ref("");
        watchEffect(() => {
            name4.value = `${user.firstName}_${user.lastName}`;
        });
        return {
            user,
            name1,
            name2,
            name3,
            name4,
        };
    },
});
</script>
<style lang="scss">
.home {
    display: flex;
    flex-direction: column;
}
</style>
